package utility;

import java.sql.*;
import javax.swing.*;


public class DBconnection_maDS {
    private static String driver = "com.mysql.cj.jdbc.Driver";
    private static String url = "jdbc:mysql://localhost:3306/myds?serverTimezone=GMT%2B8";
    private static String username = "root";
    private static String password = "root";

    static Connection con = null;
    static PreparedStatement ps = null;
    static ResultSet rs = null;
    static String sql = "SELECT * FROM";

    public DBconnection_maDS(){}

    //    静态块里的内容在类被加载的时候就执行
    static {
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            JOptionPane.showMessageDialog(null, "数据库驱动加载出错!");
        }
        try {
            con = DriverManager.getConnection(url, username, password);
            ps = con.prepareStatement(sql);
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(null,"数据库账号或密码错误");
        }
    }


    public static void main(String[] args)  {

    }
    //登录
    public static int  Login(String sql){
        int length=0;
        try {
            rs = ps.executeQuery(sql);
            if(rs.isBeforeFirst()) {
                length+=1;
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return length;
    }
    //找到用户名查看合法性
    public static int  FindUsername(String sql){
        int length=0;
        try {
            rs = ps.executeQuery(sql);
            while(rs.next())length+=1;

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return length;
    }
    //找到密保问题
    public static String FindQuestion(String sql){
        String result=null;
        try {
            rs = ps.executeQuery(sql);
            while(rs.next())result=rs.getString(1);

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return result;
    }

    //    数据库执行查询
    public static ResultSet query(String sql){
        try {
            rs = ps.executeQuery(sql);
            while(rs.next()) System.out.println(rs);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return rs;
    }

    //    数据库执行、更新、删除
    public static Boolean updateQuery(String sql){
        try {
            ps.executeUpdate(sql);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return true;
    }


    //     数据库需要关闭
    public static void close(){
        try {
            // 关闭是有顺序的：先关闭结果集，再关闭语句，再关闭连接
            if (null != rs)
                rs.close();
            if (null != ps)
                ps.close();
            if (null != con)
                con.close();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }
}